﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace CNative.Utilities
{
    /// <summary>
    /// 常用字符串处理
    /// </summary>
    public class FuncStr
    {

        /// <summary>
        /// 转换为字符串,空对象转换为空字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string NullToStr(object obj)
        {
            if (obj == null || obj == System.DBNull.Value)
                return "";
            else
                return obj.ToString().Trim();
        }


   
        /// <summary>
        /// 转换为int,空对象转换为0
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int NullToInt(object obj)
        {
            if (obj == null || obj == System.DBNull.Value) //数据库空可以不判断,系统会自动转换为null
                return 0;
            else
                return ToInt32(obj.ToString());
        }
        /// <summary>
        /// 把一个字符串类型转化为可能的整型
        /// </summary>
        /// <param name="S"></param>
        /// <returns></returns>
        public static int ToInt32(string S)
        {
            S = S.Trim();
            if (S.Trim() == "") return (0);
            if (S.IndexOf("-") >= 0)
            {   //有负号，但不是开头，则转换为0
                if (S.StartsWith("-") == false) return (0);
                if (S.StartsWith("--")) return (0);
            }
            for (int i = 0; i < S.Length; i++)
            {
                switch (S.Substring(i, 1))
                {
                    case "0":
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                    case "5":
                    case "6":
                    case "7":
                    case "8":
                    case "9":
                        break;
                    case "-":
                        if (S.Length == 1) return (0);
                        break;
                    default:
                        if (i == 0)
                            return (0);
                        else
                            try { return (Convert.ToInt32(S.Substring(0, i))); }
                            catch { return 0; }
                }
            }
            try { return (Convert.ToInt32(S)); }
            catch { return 0; }
        }
        /// <summary>
        /// 判断字符串是否包含非数字字符
        /// </summary>
        /// <returns>返回是否</returns>
        public static bool IsNumber(string str)
        {
            foreach (char _chr in str)
                if (!Char.IsNumber(_chr))
                    return false;

            return true;
        }

        /// <summary>
        /// 判断字符串是否数字
        /// </summary>
        /// <returns>返回是否</returns>
        public static bool IsNumeric(object str)
        {
            try
            {
                decimal _d = Convert.ToDecimal(str);
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 转换为Decimal,空对象转换为0.0
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Decimal NullToDecimal(object obj)
        {
            if (obj == null || obj == System.DBNull.Value)	//数据库空可以不判断,系统会自动转换为null
                return 0.0M;
            else
                return FuncStr.ToDecimal(obj.ToString());
        }
        /// <summary>
        /// 转换为double,空对象转换为0.0
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double NullToDouble(object obj)
        {
            if (obj == null || obj == System.DBNull.Value)	//数据库空可以不判断,系统会自动转换为null
                return 0.0;
            else
                return double.Parse(obj.ToString());
        }

      

        /// <summary>
        /// 把一个字符串类型转化为可能的俘点型
        /// </summary>
        /// <param name="S"></param>
        /// <returns></returns>
        public static decimal ToDecimal(string S)
        {
            bool Flag = false;
            S = S.Trim();
            if (S.Trim() == "") return (0);
            if (S.IndexOf("-") >= 0)
            {   //有负号，但不是开头，则转换为0
                if (S.StartsWith("-") == false) return (0);
                if (S.StartsWith("--")) return (0);
            }
            for (int i = 0; i < S.Length; i++)
            {
                switch (S.Substring(i, 1))
                {
                    case "0":
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                    case "5":
                    case "6":
                    case "7":
                    case "8":
                    case "9":
                        break;
                    case "-":
                        if (S.Length == 1) return (0M);
                        break;
                    case ".":
                        if (S.Length == 1) return (0M);      //只有一个点的情况
                        if (Flag == false)
                        {
                            Flag = true;
                        }
                        else
                        {   //如果出现2个点
                            if (i == 0)  //实际不可能 I=0
                                return (0M);
                            else         //取这个点之前的内容来进行计算
                                try { return (Convert.ToDecimal(S.Substring(0, i))); }
                                catch { return 0m; }
                        }
                        break;
                    default:   //出现非法数字
                        if (i == 0)
                            return (0M);
                        else
                            try { return (Convert.ToDecimal(S.Substring(0, i))); }
                            catch { return 0m; }
                }
            }
            try { return (Convert.ToDecimal(S)); }
            catch { return 0m; }
        }
        #region 返回颜色方法 ReturnColor

        /// <summary>
        /// 返回颜色方法
        /// </summary>
        /// <param name="stringColor">如蓝色Blue为:0,0,255 或 Blue</param>
        /// <returns></returns>
        public static System.Drawing.Color ReturnColor(string stringColor)
        {
            System.Drawing.Color checkColor = System.Drawing.Color.Black;
            try
            {
                if (!stringColor.IsNullOrEmpty())
                {
                    string[] ColorNum = stringColor.Split(',');
                    if (ColorNum.Length > 1)
                        checkColor = System.Drawing.Color.FromArgb(ColorNum[0].NullToInt(), ColorNum[1].NullToInt(),
                            ColorNum[2].NullToInt());
                    else
                        checkColor = System.Drawing.Color.FromName(stringColor);
                }
            }
            catch
            {
                checkColor = System.Drawing.Color.Black;
            }

            return checkColor;
        }

        #endregion
        /// <summary>
        /// 取字符串srcs左边lenn个字符组成的串
        /// </summary>
        /// <param name="srcs"></param>
        /// <param name="lenn"></param>
        /// <returns></returns>
        public static String LeftStr(String srcs, int lenn)
        {
            return MidStr(srcs, 0, lenn);
        }

        /// <summary>
        /// 取字符串srcs右边lenn个字符组成的串
        /// </summary>
        /// <param name="srcs"></param>
        /// <param name="lenn"></param>
        /// <returns></returns>
        public static String RightStr(String srcs, int lenn)
        {
            if (srcs.Length >= lenn)
                return MidStr(srcs, srcs.Length - lenn);
            else
                return srcs;
        }

        /// <summary>
        /// 取字符串srcs从startp开始到结尾的字符组成的字符串
        /// </summary>
        /// <param name="srcs"></param>
        /// <param name="startp"></param>
        /// <returns></returns>
        public static String MidStr(String srcs, int startp)
        {
            if ((startp >= 0) && (srcs.Length >= startp))
                return srcs.Substring(startp);
            else
                return "";
        }

        /// <summary>
        /// 取字符串srcs从startp开始的lenn个长度字符组成的字符串
        /// </summary>
        /// <param name="srcs"></param>
        /// <param name="startp"></param>
        /// <param name="lenn"></param>
        /// <returns></returns>
        public static String MidStr(String srcs, int startp, int lenn)
        {
            if ((startp >= 0) && (lenn > 0) && (srcs.Length >= startp))
            {
                if (lenn > srcs.Length) lenn = srcs.Length;
                return srcs.Substring(startp, lenn);
            }
            else
                return "";
        }

        /// <summary>
        /// 从字符串strs中取从startp位置开始遇到的第一个subs所在的位置
        /// </summary>
        /// <param name="strs"></param>
        /// <param name="subs"></param>
        /// <param name="startp"></param>
        /// <returns></returns>
        public static int PosStr(String strs, String subs, int startp)
        {
            if (startp >= strs.Length)
                return -1;
            else
                return strs.IndexOf(subs, startp);
        }

        /// <summary>
        /// 从字符串strs中取遇到的第一个subs所在的位置
        /// </summary>
        /// <param name="strs"></param>
        /// <param name="subs"></param>
        /// <returns></returns>
        public static int PosStr(String strs, String subs)
        {
            return PosStr(strs, subs, 0);
        }

        /// <summary>
        /// 连续按实际长度获取字符串中的数据 从第1位开始计算start
        /// </summary>
        /// <param name="Str"></param>
        /// <param name="Start"></param>
        /// <param name="Length"></param>
        /// <returns></returns>
        public static string MidStrB(string Str, int Start, int Length)
        {
            int L = LenB(Str);
            if (L < Start) return "";

            string T = "";
            for (int i = 0; i < Str.Length; i++)
            {
                if (LenB(Str.Substring(0, i + 1)) >= Start)
                    T = T + Str.Substring(i, 1);

                if (LenB(T) >= Length)
                    return MyTrim(T);
            }
            return ""; //MidStrB = MyTrim(MidStrB);
        }

        /// <summary>
        /// 字符串长度包括汉字两位
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static int LenB(string Str)
        {
            return System.Text.Encoding.Default.GetByteCount(Str);
        }

        /// <summary>
        /// 可以将Chr(0)结束的字符串截取空格
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string MyTrim(string Str)
        {
            string T = "";
            int i;

            int L = Str.Length;
            for (i = 0; i < L; i++)
            {
                T = Str.Substring(i, 1);
                if (T != " " && Convert.ToInt32(Convert.ToChar(T)) != 0)
                {
                    break;
                }
            }
            Str = Str.Substring(i, L - i);

            L = Str.Length;
            for (i = L - 1; i >= 0; i--)
            {
                T = Str.Substring(i, 1);
                if (T != " " && Convert.ToInt32(Convert.ToChar(T)) != 0)
                {
                    break;
                }
            }
            Str = Str.Substring(0, i + 1);

            return Str;
        }



        /// <summary>
        /// 字符串补空格
        /// </summary>
        /// <param name="psStr">字符串</param>
        /// <param name="piCount">总长度</param>
        /// <returns>返回传入字符串</returns>
        public static string SetStrNSP(string psStr, int piCount)
        {
            while (Encoding.Default.GetByteCount(psStr) <= piCount)
            {
                psStr += " ";
            }
            return psStr;
        }

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern int MapVirtualKey(uint uCode, uint uMapType);

        //private static char KeyCodeToChar(System.Windows.Forms.Keys k)
        //{
        //    int nonVirtualKey = MapVirtualKey((uint)k, 2);
        //    char mappedChar = Convert.ToChar(nonVirtualKey);
        //    return mappedChar;
        //}

        ///// <summary>
        ///// System.Windows.Forms.Keys类型转换为String
        ///// </summary>
        ///// <param name="k"></param>
        ///// <returns></returns>
        //public static string KeyCodeToStr(System.Windows.Forms.Keys k)
        //{
        //    char mappedChar = KeyCodeToChar(k);
        //    string str = mappedChar.ToString();
        //    if (Char.IsWhiteSpace(mappedChar) || string.IsNullOrEmpty(str) || mappedChar == '\r' || mappedChar == '\n')
        //        return k.ToString();
        //    else
        //        return str + "";
        //}

        /// <summary>
        /// 将字符串srs中标识为ids的值删除，其中dpts为分隔符，equs为等值符
        /// 字符串strs的格式为：&lt;name&gt;&lt;equs&gt;&lt;value&gt;[&lt;dpts&gt;&lt;name&gt;&lt;equs&gt;&lt;value&gt;]
        /// </summary>
        /// <param name="strs"></param>
        /// <param name="dpts"></param>
        /// <param name="equs"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static String DelParmStr(String strs, String dpts, String equs, String ids)
        {
            int pos0, pos1, pos2;
            strs = dpts + strs;
            pos0 = PosStr(strs.ToUpper(), (dpts + ids + equs).ToUpper());
            if (pos0 >= 0)
            {
                pos1 = pos0 + ((string)(dpts + ids + equs)).Length;
                pos2 = PosStr(strs, dpts, pos1);
                if (pos2 >= 0)
                {
                    if (pos0 >= 1)
                        strs = LeftStr(strs, pos0) + MidStr(strs, pos2);
                    else
                        strs = MidStr(strs, pos2);
                }
                else
                {
                    if (pos0 >= 1)
                        strs = LeftStr(strs, pos0);
                    else
                        strs = dpts;
                }
            }
            strs = MidStr(strs, dpts.Length);
            return strs;
        }

        /// <summary>
        /// 将字符串srs中标识为ids的值删除，其中dpts为分隔符，等值符为"="
        /// 字符串strs的格式为：&lt;name&gt;=&lt;value&gt;[&lt;dpts&gt;&lt;name&gt;=&lt;value&gt;]
        /// </summary>
        /// <param name="strs"></param>
        /// <param name="dpts"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static String DelParmStr(String strs, String dpts, String ids)
        {
            return DelParmStr(strs, dpts, "=", ids);
        }

        /// <summary>
        /// 将字符串srs中标识为ids的值删除，其中分隔符为";"，等值符为"="
        /// 字符串strs的格式为：&lt;name&gt;=&lt;value&gt;[;&lt;name&gt;=&lt;value&gt;]
        /// </summary>
        /// <param name="strs"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static String DelParmStr(String strs, String ids)
        {
            return DelParmStr(strs, ";", ids);
        }

        /// <summary>
        /// 将一个整数Ascii码转化为一个字符
        /// </summary>
        /// <param name="ascode"></param>
        /// <returns></returns>
        public static char Chr(int ascode)
        {
            return (char)ascode;
        }

        /// <summary>
        /// 从字符串str中取出第一个字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static char Chr(string str)
        {
            return Chr(str, 0);
        }

        /// <summary>
        /// 从字符串str中取出第chrpos个字符
        /// </summary>
        /// <param name="str"></param>
        /// <param name="chrpos"></param>
        /// <returns></returns>
        public static char Chr(string str, int chrpos)
        {
            return str.ToCharArray(chrpos, 1)[0];
        }

        /// <summary>
        /// 获取字符chr的Ascii码
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        public static int Asc(char chr)
        {
            return Convert.ToInt32(chr);
        }

        /// <summary>
        /// 获取字符串str中第一个字符的Ascii码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int Asc(string str)
        {
            return Asc(str, 0);
        }

        /// <summary>
        /// 获取字符串str中第chrpos个字符的Ascii码
        /// </summary>
        /// <param name="str"></param>
        /// <param name="chrpos"></param>
        /// <returns></returns>
        public static int Asc(string str, int chrpos)
        {
            return Asc(str.ToCharArray(chrpos, 1)[0]);
        }

        /// <summary>
        /// 获取Boolwan
        /// </summary>
        /// <param name="str"></param>
        /// <param name="nullValue"></param>
        /// <returns></returns>
        public static bool ConvertBool(string str,bool nullValue)
        {
            bool tryResult = false;
            if (Boolean.TryParse(str, out tryResult))
                return tryResult;
            else
                return nullValue;
        }

        /// <summary>
        /// 返回年龄
        /// </summary>
        /// <param name="brithday"></param>
        /// <param name="DisArea">是否汉字</param>
        /// <returns></returns>
        public static string GetAge(string brithday, bool DisArea = false)
        {
            string str = string.Empty;
            DateTime now = DateTime.Now;
            DateTime dateTime1 = DateTime.Now;
            DateTime dateTime2;
            try
            {
                dateTime2 = brithday.ToDateTime();
            }
            catch
            {
                return "";
            }
            int num1 = dateTime1.Day - dateTime2.Day;
            if (num1 < 0)
            {
                dateTime1 = dateTime1.AddMonths(-1);
                num1 += DateTime.DaysInMonth(dateTime1.Year, dateTime1.Month);
            }
            int num2 = dateTime1.Month - dateTime2.Month;
            if (num2 < 0)
            {
                num2 += 12;
                dateTime1 = dateTime1.AddYears(-1);
            }
            int num3 = dateTime1.Year - dateTime2.Year;
            if (num3 < 1)
            {
                if (num2 < 1)
                    str = num1.ToString() + "天";
                else if (num2 >= 1 && num2 < 3)
                {
                    str = num2.ToString() + "月";
                    if ((uint)num1 > 0U)
                        str = str + num1.ToString() + "天";
                }
                else if (num2 >= 3 && num2 < 12)
                    str = num2.ToString() + "月";
            }
            else if (num3 >= 1 && num3 < 14)
            {
                str = num3.ToString() + "岁";
                if ((uint)num2 > 0U)
                    str = str + num2.ToString() + "月";
            }
            else if (num3 >= 14)
                str = num3.ToString() + "岁";
            if (DisArea)
                str = str.Replace('岁', 'Y').Replace('月', 'M').Replace('天', 'D');
            return str;
        }

    }
}

